package com.jfinal.server.undertow.util;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;

public abstract class PortKit {

    private PortKit() {}

    public static int detectUsefulPort(int...precedencePorts) {
        if (precedencePorts != null) {
            for (int port : precedencePorts) {
                if (isAvailablePort(port)) {
                    return port;
                }
            }
        }
        return detectUsefulPort();
    }

    public static int detectUsefulPort() {
        try (ServerSocket serverSocket = new ServerSocket(0)) {
            return serverSocket.getLocalPort(); // 获取分配的端口号
        } catch (Exception e) {
            throw new RuntimeException("detect random port fail", e);
        }
    }

    public static boolean isAvailablePort(int port) {
        if (port <= 0) {
            throw new IllegalArgumentException("Invalid port: " + port);
        }

        boolean available = true;

        try (ServerSocket ss = new ServerSocket(port); DatagramSocket ds = new DatagramSocket(port)) {
            ss.setReuseAddress(true);
            ds.setReuseAddress(true);
        } catch (IOException ignored) {
            available = false;
        }

        return available;
    }

}
